package 多线程.生产者消费者模式;

public class App {
    public static void main(String[] args) {
        Movie movie = new Movie();
        new Thread(new Watcher(movie)).start();
        new Thread(new Player(movie)).start();

    }
}


class Movie {
    private String pic;

    private boolean flag = true;//这时生产者生产消费者等等，false时消费者消费，生产者等等


    public synchronized void player(String pic)     {

        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("生产了" + pic);
        this.pic = pic;
        this.notify();
        this.flag = false;
    }

    public synchronized void watch()   {

        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("消费了" + pic);
        this.notifyAll();
        this.flag = true;
    }
}

class Player implements Runnable {
    private Movie movie;

    public Player(Movie movie) {
        this.movie = movie;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                movie.player("无间道");
            } else movie.player("复仇者联盟");
        }
    }
}

class Watcher implements Runnable {
    private Movie movie;

    public Watcher(Movie movie) {
        this.movie = movie;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            movie.watch();
        }
    }
}
